import { configure, start, done } from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import router from './router'
import { getToken, getShopInfo } from './utils/auth' // get token from cookie
import getPageTitle from './utils/get-page-title'
configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to: any, from: any, next) => {
  // start progress bar
  // .log(to, 'from==='console)
  start()
  // determine whether the user has logged in
  const hasToken = getToken()
  let shopInfo = {
    id: ''
  }
  if (getShopInfo()) {
    shopInfo = JSON.parse(getShopInfo() as string)
  }
  if (hasToken && shopInfo.id) {
    // set page title
    document.title = getPageTitle(to.meta.title)
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      done()
    } else {
      const routes = router.getRoutes().filter((r) => r.path === to.path)
      // console.log(router.getRoutes(), 'router.getRoutes()', routes, to.path)
      if (routes.length) {
        // Permission filtering
        // const toRoute: any = routes[0]
        // if ((toRoute.meta && !toRoute.meta.roles) || (toRoute.meta && toRoute.meta.roles.includes(roles))) {
        //   next()
        // } else {
        //   next('/401')
        // }
        next()
      } else {
        // Otherwise jump to 404
        next('/404')
      }
    }
  } else {
    next()
    // /* has no token*/
    // if (whiteList.includes(to.path)) {
    //   // in the free login whitelist, go directly
    //   next()
    // } else {
    //   // other pages that do not have permission to access are redirected to the login page.
    //   next('/login')
    //   // next()
    //   done()
    // }
  }
})

router.afterEach(() => {
  // finish progress bar
  done()
})
